<template>
  <div class="document-management">
    <!-- 左侧容器 -->
    <div class="left-container">
      <!-- 文档列表容器 -->
      <div class="doc-list-container">
        <div class="section-header">
          <h3 class="container-title">文档列表</h3>
          <div class="header-actions">
            <a-select
              v-model:value="docStatusFilter"
              size="small"
              style="width: 80px; margin-right: 0;"
              :options="statusFilterOptions"
            />
            <a-upload
              :show-upload-list="false"
              :before-upload="handleBeforeUpload"
              accept=".json"
            >
              <a-button 
                type="primary" 
                class="search-btn" 
                size="small"
              >
                <i class="fas fa-upload"></i>
                上传
              </a-button>
            </a-upload>
          </div>
        </div>
        <div class="doc-list-content">
          <!-- 文档列表内容 -->
          <div class="doc-list">
            <div v-for="doc in filteredDocuments" :key="doc.id" class="doc-item" :class="{ 'active': selectedDocId === doc.id }" @click="selectDocument(doc.id)">
              <div class="doc-content">
                <div class="doc-header">
                  <div class="doc-title">{{ doc.title }}</div>
                  <a-tag v-if="doc.status !== 'success'" :color="getStatusTagColor(doc.status)" class="status-tag">
                    {{ getStatusText(doc.status) }}
                  </a-tag>
                </div>
                <div class="doc-meta">
                  <span class="doc-date">{{ doc.date }}</span>
                  <div class="doc-actions">
                    <a-button type="text" class="action-btn" danger @click.stop="confirmDelete(doc.id)">
                      <DeleteOutlined />
                    </a-button>
                  </div>
                </div>
              </div>
              
              <!-- 状态遮罩层 - 仅在非成功状态下显示 -->
              <div v-if="doc.status && doc.status !== 'success'" class="status-overlay">
                <div class="doc-content blur-content"></div>
                <div class="status-content">
                  <div class="status-header">
                    <!-- 左侧容器：标题和状态 -->
                    <div class="status-left">
                      <div class="status-title">{{ doc.title }}</div>
                      <a-tooltip :title="getStatusTooltip(doc.status)" placement="top">
                        <div class="status-badge" :class="getStatusClass(doc.status)">
                          <i :class="getStatusIcon(doc.status)"></i>
                          {{ getStatusText(doc.status) }}
            </div>
                      </a-tooltip>
          </div>
          
                    <!-- 右侧容器：操作按钮 -->
                    <div class="status-actions">
                      <!-- 开始按钮 - 仅待嵌入状态显示 -->
                      <a-tooltip title="开始嵌入" placement="top">
                        <i 
                          v-if="doc.status === 'pending'" 
                          class="fas fa-arrow-right status-icon start-icon" 
                          @click.stop="startEmbedding(doc)"
                        ></i>
                      </a-tooltip>
                      
                      <!-- 取消按钮 - 仅排队中和嵌入中显示 -->
                      <a-tooltip title="取消" placement="top">
                        <i 
                          v-if="['queued', 'embedding'].includes(doc.status)" 
                          class="fas fa-times status-icon cancel-icon" 
                          @click.stop="cancelEmbedding(doc)"
                        ></i>
                      </a-tooltip>
                      
                      <!-- 重试按钮 - 仅嵌入失败显示 -->
                      <a-tooltip title="重试" placement="top">
                        <i 
                          v-if="doc.status === 'failed'" 
                          class="fas fa-arrow-rotate-right status-icon retry-icon" 
                          @click.stop="retryEmbedding(doc)"
                        ></i>
                      </a-tooltip>
                      
                      <!-- 删除按钮 - 所有非成功状态显示 -->
                      <a-tooltip title="删除" placement="top">
                        <i 
                          class="fas fa-trash status-icon delete-icon" 
                          @click.stop="confirmDelete(doc.id)"
                        ></i>
                      </a-tooltip>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 无数据时显示 -->
            <div v-if="filteredDocuments.length === 0" class="empty-list">
              <p>暂无{{ getStatusFilterName() }}文档</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 筛选条件容器 -->
      <div class="filter-container">
        <div class="section-header">
          <h3 class="container-title">概要</h3>
        </div>
        <div class="filter-content">
          <!-- 概要表格 -->
          <table class="summary-table">
            <tbody>
              <tr>
                <td class="label">版本</td>
                <td class="value">V1.0.0</td>
              </tr>
              <tr>
                <td class="label">描述</td>
                <td class="value">知识图谱关系可视化</td>
              </tr>
              <tr>
                <td class="label">类型</td>
                <td class="value">API接口图谱</td>
              </tr>
              <tr>
                <td class="label">实体数</td>
                <td class="value">120</td>
              </tr>
              <tr>
                <td class="label">关系数</td>
                <td class="value">95</td>
              </tr>
            </tbody>
          </table>
        </div>
            </div>
          </div>
          
    <!-- 右侧容器 -->
    <div class="right-container">
      <div class="right-header">
        <h3 class="container-title">关系图谱</h3>
        <div class="header-actions">
          <a-button 
            type="primary" 
            class="refresh-btn" 
            @click="refreshGraph"
            size="small"
          >
            <i class="fas fa-sync-alt"></i>
            刷新图谱
          </a-button>
          <a-button 
            type="default"
            class="history-btn"
            @click="showHistoryVersions"
            size="small"
          >
            <i class="fas fa-history"></i>
            历史版本
          </a-button>
          <a-button 
            type="primary"
            class="archive-btn"
            @click="archiveVersion"
            size="small"
          >
            <i class="fas fa-save"></i>
            版本归档
          </a-button>
        </div>
      </div>
      <div class="right-content">
        <RelationMap v-if="currentDocument || isGraphRefreshed" ref="relationMapRef" :document="currentDocument" />
        <div v-else class="no-document-selected">
          <p>请从左侧列表选择一个文档</p>
        </div>
            </div>
          </div>
          
    <!-- 删除确认弹窗 -->
    <a-modal
      v-model:visible="deleteModalVisible"
      title="确认删除"
      :centered="true"
      :closable="true"
      :maskClosable="true"
      :keyboard="true"
      :footer="null"
    >
      <a-alert
        type="warning"
        message="删除文档不影响已归档数据"
        description="此操作仅删除文档本身，所有已经归档的实体和关系数据将会保留。"
        banner
        style="margin-bottom: 16px"
      />
      <p>确定要删除文档 <b>{{ documentToDelete?.title || ''}}</b> 吗？</p>
      <div class="modal-footer">
        <a-button key="cancel" @click="deleteModalVisible = false">取消</a-button>
        <a-button key="confirm" type="primary" danger @click="handleDeleteConfirm">
          删除
        </a-button>
            </div>
    </a-modal>
    
    <!-- 版本归档弹窗 -->
    <a-modal
      v-model:visible="archiveModalVisible"
      :title="null"
      :centered="true"
      :maskClosable="false"
      :footer="null"
      style="width:30%"
      destroyOnClose
    >
      <div class="archive-title">
        <i class="fas fa-save"></i>
        <span>版本归档</span>
          </div>
      <div class="archive-form">
        <div class="form-item">
          <div class="form-label">版本号</div>
          <div class="form-input-wrap">
            <input
              class="version-input"
              type="text"
              placeholder="请输入版本号（如 V1.0.4）"
              v-model="archiveVersionValue"
            />
        </div>
      </div>
        <div class="form-item">
          <div class="form-label">版本描述</div>
          <div class="form-input-wrap">
            <textarea
              class="version-desc"
              placeholder="请输入版本描述"
              rows="3"
              v-model="archiveDescValue"
            ></textarea>
    </div>
        </div>
      </div>
      <div class="modal-footer">
        <a-button @click="archiveModalVisible = false">取消</a-button>
        <a-button type="primary" @click="handleArchiveConfirm">确认归档</a-button>
      </div>
    </a-modal>
    
    <!-- 历史版本弹窗 -->
    <a-modal
      v-model:visible="historyModalVisible"
      title="历史版本"
      :centered="true"
      style="width:50%; margin-top: 0;"
      destroyOnClose
    >
      <div class="history-versions">
        <table class="history-table">
          <thead>
            <tr>
              <th style="width: 20%">版本号</th>
              <th style="width: 25%">归档日期</th>
              <th style="width: 15%">实体数</th>
              <th style="width: 15%">关系数</th>
              <th style="width: 25%">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="version in paginatedHistoryVersions" :key="version.version">
              <td class="version-cell">
                <span class="version-badge">{{ version.version }}</span>
              </td>
              <td>{{ version.date }}</td>
              <td>
                <span class="entity-count">{{ version.entities }}</span>
              </td>
              <td>
                <span class="relation-count">{{ version.relations }}</span>
              </td>
              <td class="action-cell">
                <button class="rollback-btn" @click="rollbackVersion(version)">
                  <i class="anticon">
                    <svg
                      viewBox="64 64 896 896"
                      focusable="false"
                      data-icon="rollback"
                      width="1em"
                      height="1em"
                      fill="currentColor"
                      aria-hidden="true"
                    >
                      <path d="M793 242H366v-74c0-6.7-7.7-10.4-12.9-6.3l-142 112a8 8 0 000 12.6l142 112c5.2 4.1 12.9.4 12.9-6.3v-74h415v470H175c-4.4 0-8 3.6-8 8v60c0 4.4 3.6 8 8 8h618c35.3 0 64-28.7 64-64V306c0-35.3-28.7-64-64-64z"></path>
                    </svg>
                  </i>
                  回退
                </button>
                <button class="delete-btn" @click="deleteVersion(version)">
                  <i class="anticon">
                    <svg
                      viewBox="64 64 896 896"
                      focusable="false"
                      data-icon="delete"
                      width="1em"
                      height="1em"
                      fill="currentColor"
                      aria-hidden="true"
                    >
                      <path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"></path>
                    </svg>
                  </i>
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
        
        <!-- 分页控件 -->
        <div class="pagination-container">
          <div class="pagination">
            <button 
              class="pagination-btn" 
              :disabled="currentPage === 1"
              @click="changePage(currentPage - 1)"
            >
              <i class="fas fa-chevron-left"></i>
            </button>
            <span class="pagination-info">{{ currentPage }} / {{ totalPages }}</span>
            <button 
              class="pagination-btn" 
              :disabled="currentPage === totalPages"
              @click="changePage(currentPage + 1)"
            >
              <i class="fas fa-chevron-right"></i>
            </button>
      </div>
      </div>
    </div>
      <template #footer>
        <a-button type="primary" @click="historyModalVisible = false">关闭</a-button>
      </template>
    </a-modal>
    
    <!-- 版本回退确认弹窗 -->
    <a-modal
      v-model:visible="rollbackModalVisible"
      title="确认恢复"
      :centered="true"
      :closable="true"
      :maskClosable="true"
      :footer="null"
      destroyOnClose
    >
      <p>确定要恢复到版本 <b>{{ versionToRollback?.version || '' }}</b> 吗？恢复后将覆盖当前版本数据。</p>
      <div class="modal-footer">
        <a-button @click="rollbackModalVisible = false">取消</a-button>
        <a-button type="primary" @click="handleRollbackConfirm">确认</a-button>
      </div>
    </a-modal>
    
    <!-- 版本删除确认弹窗 -->
    <a-modal
      v-model:visible="deleteVersionModalVisible"
      title="确认删除"
      :centered="true"
      :closable="true"
      :maskClosable="true"
      :footer="null"
      destroyOnClose
    >
      <p>确定要删除版本 <b>{{ versionToDelete?.version || '' }}</b> 吗？删除后将无法恢复。</p>
      <div class="modal-footer">
        <a-button @click="deleteVersionModalVisible = false">取消</a-button>
        <a-button type="primary" danger @click="handleDeleteVersionConfirm">删除</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
// 文档管理组件
import { ref, computed, onMounted, watch, reactive, nextTick, h } from 'vue';
import { DeleteOutlined } from '@ant-design/icons-vue';
import RelationMap from './RelationMap.vue';
import { message, Modal } from 'ant-design-vue';

// 标签容器引用
const relationTagsContainer = ref(null);
const fieldTagsContainer = ref(null);

// 示例文档列表数据 - 修改为响应式数组
const documentList = reactive([
  {
    id: 1,
    title: '网络安全报告2023',
    date: '2023-05-15',
    entityCount: 24,
    relationCount: 17,
    status: 'success' // 嵌入成功
  },
  {
    id: 2,
    title: '人工智能发展白皮书',
    date: '2023-06-22',
    entityCount: 38,
    relationCount: 42,
    status: 'pending' // 待嵌入
  },
  {
    id: 3,
    title: '大数据技术趋势分析',
    date: '2023-07-10',
    entityCount: 31,
    relationCount: 26,
    status: 'queued' // 排队中
  },
  {
    id: 4,
    title: '企业数字化转型指南',
    date: '2023-08-05',
    entityCount: 19,
    relationCount: 15,
    status: 'embedding' // 嵌入中
  },
  {
    id: 5,
    title: '5G技术应用场景研究',
    date: '2023-09-18',
    entityCount: 27,
    relationCount: 20,
    status: 'failed' // 嵌入失败
  },
  {
    id: 6,
    title: '云计算安全架构设计',
    date: '2023-10-24',
    entityCount: 45,
    relationCount: 38,
    status: 'success'
  },
  {
    id: 7,
    title: '区块链在金融领域的应用',
    date: '2023-11-30',
    entityCount: 36,
    relationCount: 29,
    status: 'success'
  },
  {
    id: 8,
    title: '物联网和智能家居',
    date: '2024-01-15',
    entityCount: 28,
    relationCount: 22,
    status: 'success'
  },
  {
    id: 9,
    title: '量子计算研究进展',
    date: '2024-02-20',
    entityCount: 33,
    relationCount: 19,
    status: 'success'
  },
  {
    id: 10,
    title: '边缘计算技术白皮书',
    date: '2024-03-05',
    entityCount: 21,
    relationCount: 16,
    status: 'success'
  },
  {
    id: 11,
    title: '网络协议安全分析',
    date: '2024-03-28',
    entityCount: 42,
    relationCount: 35,
    status: 'success'
  }
]);

// 文档状态筛选
const docStatusFilter = ref('success'); // 默认展示成功文档

// 状态筛选选项
const statusFilterOptions = [
  { value: 'success', label: '已嵌入' },
  { value: 'pending', label: '未嵌入' }
];

// 获取状态筛选名称
const getStatusFilterName = () => {
  const filterMap = {
    'success': '已完成',
    'pending': '处理中'
  };
  return filterMap[docStatusFilter.value] || '';
};

// 筛选文档列表
const filteredDocuments = computed(() => {
  if (docStatusFilter.value === 'success') {
    return documentList.filter(doc => doc.status === 'success');
  } else if (docStatusFilter.value === 'pending') {
    return documentList.filter(doc => doc.status !== 'success');
  }
  return documentList.filter(doc => doc.status === 'success'); // 默认返回成功文档
});

// 选中的文档ID
const selectedDocId = ref(null);

// 当前选中的文档详情
const currentDocument = computed(() => {
  if (!selectedDocId.value) return null;
  return documentList.find(doc => doc.id === selectedDocId.value);
});

// 选择文档
const selectDocument = (id) => {
  selectedDocId.value = id;
};

// 编辑文档改为查看文档
const viewDocument = (id) => {
  // 因为不再需要查看功能，直接选中文档即可
  selectDocument(id);
};

// 删除确认弹窗状态
const deleteModalVisible = ref(false);
const documentToDelete = ref(null);

// 确认删除
const confirmDelete = (id) => {
  documentToDelete.value = documentList.find(doc => doc.id === id);
  deleteModalVisible.value = true;
};

// 处理删除确认
const handleDeleteConfirm = () => {
  if (!documentToDelete.value) return;
  
  const id = documentToDelete.value.id;
  // 从列表中移除文档
  const index = documentList.findIndex(doc => doc.id === id);
  if (index !== -1) {
    documentList.splice(index, 1);
    
    // 如果删除的是当前选中的文档，则清除选中状态
    if (selectedDocId.value === id) {
      selectedDocId.value = null;
      // 尝试选中列表中的第一个文档
      if (filteredDocuments.value.length > 0) {
        selectedDocId.value = filteredDocuments.value[0].id;
      }
    }
    
    message.success('文档已删除');
  }
  
  // 关闭弹窗
  deleteModalVisible.value = false;
  documentToDelete.value = null;
};

// 删除文档 - 直接调用删除确认
const deleteDocument = (id) => {
  confirmDelete(id);
};

// 当状态筛选改变时，重置页码
watch(docStatusFilter, () => {
  // 如果选择了新的筛选条件，且当前选中的文档不在筛选结果中，则清除选中状态
  if (selectedDocId.value) {
    const isDocumentInFilteredList = filteredDocuments.value.some(doc => doc.id === selectedDocId.value);
    if (!isDocumentInFilteredList) {
      selectedDocId.value = null;
    }
  }
});

// 初始化
onMounted(() => {
  // 初始默认选中第一个文档
  if (filteredDocuments.value.length > 0) {
    selectedDocId.value = filteredDocuments.value[0].id;
  }
});

// 处理文件上传前的验证
const handleBeforeUpload = (file) => {
  // 验证文件类型
  const isJSON = file.type === 'application/json' || file.name.endsWith('.json');
  if (!isJSON) {
    // 使用 Ant Design Vue 的消息提示
    message.error('只能上传JSON文件!');
    return false;
  }
  
  // 读取文件内容
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = (e) => {
    try {
      // 尝试解析JSON
      const content = e.target.result;
      const jsonData = JSON.parse(content);
      
      // 添加到文档列表
      addDocument(file.name, jsonData);
      message.success(`文件 ${file.name} 已上传成功，等待嵌入`);
    } catch (error) {
      message.error(`文件解析失败: ${error.message}`);
    }
  };
  
  // 阻止默认上传行为
  return false;
};

// 添加文档到列表
const addDocument = (fileName, data) => {
  // 生成唯一ID
  const newId = documentList.length > 0 ? Math.max(...documentList.map(doc => doc.id)) + 1 : 1;
  
  // 从文件名中提取标题，移除.json后缀
  const title = fileName.replace(/\.json$/, '');
  
  // 创建当前日期字符串
  const today = new Date();
  const dateStr = today.toISOString().slice(0, 10).replace(/-/g, '-');
  
  // 创建新文档对象
  const newDoc = {
    id: newId,
    title: title,
    date: dateStr,
    entityCount: 0, // 初始化为0，后续可根据JSON内容更新
    relationCount: 0, // 初始化为0，后续可根据JSON内容更新
    status: 'pending', // 设置为待嵌入状态
    data: data // 存储原始数据
  };
  
  // 添加到文档列表
  documentList.unshift(newDoc);
  
  // 如果当前筛选是显示待嵌入文档，则选中新上传的文档
  if (docStatusFilter.value === 'pending') {
    selectedDocId.value = newDoc.id;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待嵌入',
    'queued': '排队中',
    'embedding': '嵌入中',
    'failed': '嵌入失败',
    'success': '嵌入成功'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态提示信息
const getStatusTooltip = (status) => {
  const tooltipMap = {
    'pending': '文档等待嵌入处理',
    'queued': '文档正在排队等待处理',
    'embedding': '文档正在进行嵌入处理',
    'failed': '文档嵌入处理失败',
    'success': '文档已成功嵌入'
  };
  return tooltipMap[status] || '未知状态';
};

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'pending': 'status-pending',
    'queued': 'status-queued',
    'embedding': 'status-embedding',
    'failed': 'status-failed',
    'success': 'status-success'
  };
  return classMap[status] || '';
};

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    'pending': 'fas fa-hourglass-start',
    'queued': 'fas fa-clock',
    'embedding': 'fas fa-spinner fa-spin',
    'failed': 'fas fa-exclamation-circle',
    'success': 'fas fa-check-circle'
  };
  return iconMap[status] || 'fas fa-question-circle';
};

// 取消嵌入
const cancelEmbedding = (doc) => {
  if(['queued', 'embedding'].includes(doc.status)) {
    doc.status = 'pending';
    console.log(`已取消文档嵌入：${doc.title}`);
  }
};

// 重试嵌入
const retryEmbedding = (doc) => {
  if(doc.status === 'failed') {
    doc.status = 'queued';
    console.log(`重新开始嵌入文档：${doc.title}`);
  }
};

// 开始嵌入
const startEmbedding = (doc) => {
  if(doc.status === 'pending') {
    doc.status = 'queued';
    console.log(`开始嵌入文档：${doc.title}`);
  }
};

// 获取状态标签颜色
const getStatusTagColor = (status) => {
  const colorMap = {
    'pending': 'gold',
    'queued': 'blue',
    'embedding': 'purple',
    'failed': 'red'
  };
  return colorMap[status] || 'default';
};

// 引用关系图组件
const relationMapRef = ref(null);

// 刷新状态 - 初始为true，以便首次自动显示图谱
const isGraphRefreshed = ref(true);

// 刷新图谱
const refreshGraph = () => {
  console.log('刷新图谱');
  isGraphRefreshed.value = true;
  
  // 如果已有图谱实例，则调用其刷新方法
  if (relationMapRef.value) {
    // 使用nextTick确保DOM更新后再调用子组件方法
    nextTick(() => {
      relationMapRef.value.refreshGraphData();
    });
  }
};

// 版本归档状态变量
const archiveModalVisible = ref(false);
const archiveVersionValue = ref('');
const archiveDescValue = ref('');

// 历史版本状态变量
const historyModalVisible = ref(false);
const historyVersions = ref([
  { version: 'V1.0.3', date: '2023-08-15', entities: 120, relations: 95 },
  { version: 'V1.0.2', date: '2023-07-20', entities: 105, relations: 82 },
  { version: 'V1.0.1', date: '2023-06-10', entities: 98, relations: 76 },
  { version: 'V1.0.0', date: '2023-05-01', entities: 85, relations: 68 },
  { version: 'V0.9.3', date: '2023-04-15', entities: 78, relations: 62 },
  { version: 'V0.9.2', date: '2023-03-22', entities: 65, relations: 54 },
  { version: 'V0.9.1', date: '2023-02-18', entities: 52, relations: 42 },
  { version: 'V0.9.0', date: '2023-01-05', entities: 45, relations: 35 },
]);

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(5);

// 计算当前页的历史版本
const paginatedHistoryVersions = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return historyVersions.value.slice(startIndex, startIndex + pageSize.value);
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(historyVersions.value.length / pageSize.value);
});

// 切换页码
const changePage = (page) => {
  currentPage.value = page;
};

// 版本回退状态变量
const rollbackModalVisible = ref(false);
const versionToRollback = ref(null);

// 版本删除状态变量
const deleteVersionModalVisible = ref(false);
const versionToDelete = ref(null);

// 显示版本归档弹窗
const archiveVersion = () => {
  if (!currentDocument.value) {
    message.warning('请先选择一个文档');
    return;
  }
  
  // 设置默认版本号
  archiveVersionValue.value = `V1.0.${currentDocument.value.id}`;
  archiveDescValue.value = '';
  archiveModalVisible.value = true;
};

// 处理版本归档确认
const handleArchiveConfirm = () => {
  if (!archiveVersionValue.value) {
    message.error('请输入版本号');
    return;
  }
  
  // 显示加载状态
  message.loading({ content: '正在归档当前版本...', key: 'archiving' });
  
  // 模拟归档操作
  setTimeout(() => {
    message.success({ content: `版本 ${archiveVersionValue.value} 归档成功`, key: 'archiving' });
    archiveModalVisible.value = false;
  }, 1500);
};

// 显示历史版本弹窗
const showHistoryVersions = () => {
  if (!currentDocument.value) {
    message.warning('请先选择一个文档');
    return;
  }
  
  // 重置到第一页
  currentPage.value = 1;
  historyModalVisible.value = true;
};

// 回退版本
const rollbackVersion = (version) => {
  versionToRollback.value = version;
  rollbackModalVisible.value = true;
};

// 处理回退确认
const handleRollbackConfirm = () => {
  if (!versionToRollback.value) return;
  
  message.success(`已恢复到版本 ${versionToRollback.value.version}`);
  rollbackModalVisible.value = false;
  versionToRollback.value = null;
  historyModalVisible.value = false;
};

// 删除版本
const deleteVersion = (version) => {
  versionToDelete.value = version;
  deleteVersionModalVisible.value = true;
};

// 处理删除版本确认
const handleDeleteVersionConfirm = () => {
  if (!versionToDelete.value) return;
  
  // 模拟删除操作
  const versionIndex = historyVersions.value.findIndex(v => v.version === versionToDelete.value.version);
  if (versionIndex !== -1) {
    historyVersions.value.splice(versionIndex, 1);
  }
  
  message.success(`已删除版本 ${versionToDelete.value.version}`);
  deleteVersionModalVisible.value = false;
  versionToDelete.value = null;
};
</script>

<style scoped>
.document-management {
  width: 100%;
  height: 81vh;
  display: flex;
  gap: 12px;
  padding: 0.5%;
  box-sizing: border-box;
}

/* 左侧容器样式 */
.left-container {
  width: 16.67%; /* 宽度比例为1 */
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 文档列表容器 */
.doc-list-container {
  flex: 0.67; /* 占左侧容器65%的高度 */
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 筛选条件容器 */
.filter-container {
  flex: 0.33; /* 占左侧容器35%的高度 */
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 右侧容器样式 */
.right-container {
  width: 83.33%; /* 宽度比例为5 */
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 各容器头部样式 */
.section-header, .right-header {
  height: 42px;
  padding: 0 12px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

/* 容器标题样式 */
.container-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #262626;
}

/* 容器内容区域样式 */
.doc-list-content, .filter-content, .right-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

/* 文档列表样式 */
.doc-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.doc-item {
  position: relative;
  padding: 0;
  margin-bottom: 6px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.2s;
  display: flex;
  align-items: stretch;
  border: 1px solid #f0f0f0;
  height: 60px; /* 固定高度 */
  min-height: 60px; /* 设置最小高度，防止内容过少时显示异常 */
}

.doc-item:hover {
  border-color: #d9d9d9;
  background-color: #fafafa;
}

.doc-item.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.doc-content {
  flex: 1;
  padding: 8px 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.doc-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
}

.doc-title {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  text-align: left;
  max-width: 140px;
}

.doc-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #8c8c8c;
}

.doc-stats {
  display: flex;
  gap: 8px;
  font-size: 12px;
}

.entity-count {
  color: #722ed1;
}

.relation-count {
  color: #1890ff;
}

.doc-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s;
}

.doc-item:hover .doc-actions {
  opacity: 1;
}

.action-btn {
  padding: 0;
  height: 24px;
  width: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 空列表状态 */
.empty-list {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 150px;
  color: #bfbfbf;
  font-size: 14px;
}

/* 文档详情样式 */
.document-detail {
  padding: 16px;
}

.detail-title {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  margin-bottom: 12px;
}

.detail-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
  font-size: 14px;
  color: #8c8c8c;
}

.detail-stats {
  display: flex;
  gap: 16px;
}

.detail-placeholder {
  margin-top: 32px;
  text-align: center;
  color: #bfbfbf;
}

.no-document-selected {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #bfbfbf;
  font-size: 16px;
}

/* 隐藏原生滚动条 */
.doc-list-content::-webkit-scrollbar,
.filter-content::-webkit-scrollbar,
.right-content::-webkit-scrollbar {
  width: 6px;
}

.doc-list-content::-webkit-scrollbar-track,
.filter-content::-webkit-scrollbar-track,
.right-content::-webkit-scrollbar-track {
  background: transparent;
}

.doc-list-content::-webkit-scrollbar-thumb,
.filter-content::-webkit-scrollbar-thumb,
.right-content::-webkit-scrollbar-thumb {
  background-color: transparent;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.doc-list-content:hover::-webkit-scrollbar-thumb,
.filter-content:hover::-webkit-scrollbar-thumb,
.right-content:hover::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
}

/* 头部操作区域 */
.header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 12px;
}

.upload-btn {
  min-width: auto;
  line-height: 1;
  padding: 0;
}

.search-btn {
  font-size: 12px;
  height: 24px;
  padding: 0 8px;
}

.search-btn i {
  font-size: 12px;
  margin-right: 4px;
}

.fas {
  font-size: 14px;
  /* display: flex;
  align-items: center;
  justify-content: center; */
}

/* 状态遮罩层样式 */
.status-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  border-radius: 4px; /* 添加边框弧度，与文档项目弧度一致 */
  overflow: hidden; /* 确保内容不会超出圆角边界 */
}

/* 模糊效果 */
.blur-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  filter: blur(35px) opacity(0.5); /* 大幅增加模糊度至25px，降低透明度至0.1 */
  pointer-events: none;
  background-color: #f2f2f2; /* 添加背景色以增强模糊效果 */
  backdrop-filter: blur(12px); /* 增加backdrop-filter强度 */
  transform: scale(1.05); /* 稍微放大模糊内容，确保边缘不会出现空白 */
}

.status-content {
  text-align: center;
  color: white;
  width: 100%;
  padding: 0 12px;
  position: relative;
  z-index: 11;
}

/* 状态头部（标题+状态标签）*/
.status-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 16px;
}

/* 左侧状态容器 */
.status-left {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 6px;
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.status-title {
  font-weight: 500;
  font-size: 14px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  max-width: 100%;
  text-align: left;
}

/* 状态操作图标 */
.status-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  min-width: 100px;
  width: 100px;
  opacity: 0; /* 默认隐藏 */
  transition: opacity 0.25s ease; /* 添加过渡效果 */
}

/* 鼠标悬停在遮罩层上时显示操作按钮 */
.status-overlay:hover .status-actions {
  opacity: 1;
}

.status-badge {
  display: inline-flex;
  align-items: center;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: 500;
  white-space: nowrap;
  background-color: rgba(0, 0, 0, 0.5);
  line-height: 1.2;
}

.status-badge i {
  margin-right: 3px;
  font-size: 9px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  position: relative;
  top: 0;
}

.status-pending {
  background-color: rgba(250, 173, 20, 0.85);
  color: #fff;
}

.status-queued {
  background-color: rgba(24, 144, 255, 0.85);
  color: #fff;
}

.status-embedding {
  background-color: rgba(114, 46, 209, 0.85);
  color: #fff;
}

.status-failed {
  background-color: rgba(245, 34, 45, 0.85);
  color: #fff;
}

.status-success {
  background-color: rgba(82, 196, 26, 0.85);
  color: #fff;
}

.status-icon {
  font-size: 10px;
  cursor: pointer;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2); /* 统一背景不透明度 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.status-icon:hover {
  background-color: rgba(255, 255, 255, 0.35); /* 增强悬停效果 */
  transform: scale(1.1);
}

.cancel-icon {
  color: #fff;
  margin-right: 10px;
}

.retry-icon {
  color: #52c41a;
  margin-right: 10px;
}

.start-icon {
  color: #1890ff;
  margin-right: 10px;
}

.delete-icon {
  color: #ff4d4f;
}

/* 概要表格样式 */
.summary-table {
  margin-bottom: 0;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
}

.summary-table tr {
  border-bottom: 1px solid #f0f0f0;
}

.summary-table tr:last-child {
  border-bottom: none;
}

.summary-table td {
  padding: 6px 12px;
  font-size: 13px;
  text-align: left;
}

.summary-table .label {
  color: #8c8c8c;
  width: 70px;
  text-align: left;
}

.summary-table .value {
  color: #262626;
  font-weight: 500;
  text-align: left;
}

/* 筛选内容区域 */
.filter-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 8px 0 8px;
}

.refresh-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 32px;
  font-size: 14px;
  transition: all 0.3s;
}

.refresh-btn:hover {
  color: #1890ff;
  background-color: #f0f7ff;
}

.refresh-btn i {
  font-size: 14px;
}

/* 添加状态标签样式 */
.status-tag {
  font-size: 10px;
  line-height: 1;
  margin-left: 4px;
  padding: 0px 4px;
  height: 16px;
  display: flex;
  align-items: center;
}

/* 上传按钮样式 */
:deep(.ant-upload) {
  display: inline-block;
}

/* 弹窗底部样式 */
.modal-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  gap: 8px;
}

/* 头部按钮样式 */
.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.archive-btn,
.history-btn,
.refresh-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 28px;
  font-size: 12px;
  padding: 0 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.archive-btn i,
.history-btn i,
.refresh-btn i {
  font-size: 12px;
  margin-right: 4px;
}

.archive-btn {
  background-color: #52c41a;
  border-color: #52c41a;
}

.archive-btn:hover {
  background-color: #73d13d;
  border-color: #73d13d;
}

.history-btn {
  color: #595959;
}

.history-btn:hover {
  color: #1890ff;
  border-color: #1890ff;
}

/* 历史版本表格样式 */
.history-versions {
  margin-top: 8px;
}

.history-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  font-size: 14px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  table-layout: fixed;
  margin-bottom: 16px;
}

.history-table th, 
.history-table td {
  padding: 14px 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.history-table th {
  background-color: #fafafa;
  font-weight: 500;
  color: #262626;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.history-table th:first-child {
  border-left: 1px solid #f0f0f0;
  border-top-left-radius: 8px;
}

.history-table th:last-child {
  border-right: 1px solid #f0f0f0;
  border-top-right-radius: 8px;
}

.history-table td {
  background-color: white;
}

.history-table td:first-child {
  border-left: 1px solid #f0f0f0;
}

.history-table td:last-child {
  border-right: 1px solid #f0f0f0;
}

.history-table tr:last-child td:first-child {
  border-bottom-left-radius: 8px;
}

.history-table tr:last-child td:last-child {
  border-bottom-right-radius: 8px;
}

.history-table tr:last-child td {
  border-bottom: 1px solid #f0f0f0;
}

.history-table tr:hover td {
  background-color: #fafafa;
}

.version-cell {
  font-weight: 500;
}

.version-badge {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.entity-count {
  color: #722ed1;
  font-weight: 500;
}

.relation-count {
  color: #1890ff;
  font-weight: 500;
}

.action-cell {
  white-space: nowrap;
  text-align: center;
}

.rollback-btn, 
.delete-btn {
  background: none;
  border: 1px solid #d9d9d9;
  cursor: pointer;
  padding: 5px 12px;
  border-radius: 4px;
  transition: all 0.3s;
  margin-right: 8px;
  font-size: 13px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.rollback-btn {
  color: #1890ff;
  border-color: #1890ff;
}

.rollback-btn:hover {
  background-color: #e6f7ff;
}

.delete-btn {
  color: #ff4d4f;
  border-color: #ff4d4f;
}

.delete-btn:hover {
  background-color: #fff1f0;
}

.rollback-btn i, 
.delete-btn i {
  font-size: 14px;
  margin-right: 6px;
}

/* 版本归档表单样式 */
.archive-form {
  margin-top: 12px;
}

.archive-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.archive-title i {
  color: #52c41a;
  font-size: 16px;
}

.form-item {
  margin-bottom: 16px;
}

.form-label {
  font-size: 14px;
  margin-bottom: 8px;
  color: #262626;
  font-weight: 500;
}

.form-input-wrap {
  position: relative;
}

.version-input {
  width: 100%;
  height: 36px;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 14px;
}

.version-input:hover,
.version-desc:hover {
  border-color: #40a9ff;
}

.version-input:focus,
.version-desc:focus {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  outline: none;
}

.version-desc {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  transition: all 0.3s;
  resize: vertical;
  font-size: 14px;
  min-height: 80px;
}

/* 分页控件样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
  margin-bottom: 8px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 12px;
}

.pagination-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #d9d9d9;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-btn:hover:not(:disabled) {
  color: #1890ff;
  border-color: #1890ff;
}

.pagination-btn:disabled {
  color: #d9d9d9;
  cursor: not-allowed;
}

.pagination-info {
  font-size: 14px;
  color: #595959;
}
</style> 